package com.hsq.jdbc.resultset_;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

public class PreparedStatement_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入管理员的名字：");
        String admin_name = scanner.nextLine();
        System.out.println("请输入管理员的密码：");
        String admin_password = scanner.nextLine();

        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        //1.注册驱动
        Class.forName(driver);
        //2.得到连接
        Connection connection = DriverManager.getConnection(url, user, password);
        //3.得到preparedStatement
        //3.1组织SQL语句，？相当于占位符
        String sql = "select name, pwd from admin where name = ? and pwd = ?";
//      3.2     preparedStatement对象实现了PrepareStarement接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //3.3给？复制
        preparedStatement.setString(1, admin_name);
        preparedStatement.setString(2, admin_password);
        //4. 执行select语句使用executeQuery()
        //如果执行的是dml（update，insert，delete）使用executeUpdate()
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            System.out.println("登入成功");
        }
        else {
            System.out.println("Wrong!!!");
        }
        //Sql输入用户名为：1' or
        //输入万能密码：or '1' = '1
        //如果使用Statement则以上可以登入
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

}
